import 'dart:async';
import 'dart:ffi';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

void main() {
  var onError = FlutterError.onError;
  FlutterError.onError = (FlutterErrorDetails details) {
    onError?.call(details);
    // ... 处理上报逻辑，此处是flutter自己捕获的异常
  };

  runZoned(() => runApp(const MyApp()),
      // 异常配置
      zoneSpecification: ZoneSpecification(
        // 捕获打印
        print: (Zone self, ZoneDelegate parent, Zone zone, String line) {
          // ...收集日志
          // ...
          // 打印 此处可判断是否是debug模式下，如果是再打印
          parent.// print(zone, "Interceptor: $line");
        },
        // 捕获未处理的异步异常
        handleUncaughtError: (self, parent, zone, error, stackTrace) {
          parent.// print(zone, '${error.toString()} $stackTrace');
          // 处理异常
          // 。。。
        },
      ));
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
            seedColor: const Color.fromARGB(255, 66, 157, 218)),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'APP Name'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
        length: 3, // 需要和tabbar的数量一致
        child: Scaffold(
            appBar: AppBar(
              title: const Text("pageView"),
              bottom:
                  TabBar(tabs: [Text('xinwen'), Text('lishi'), Text("data")]),
            ),
            body: TabBarView(
              children: [
                PageViewTest("1"),
                PageViewTest("2"),
                const WillPopScopeTestRoute()
              ],
            )));
  }
}

// ignore: must_be_immutable
class PageViewTest extends StatefulWidget {
  PageViewTest(this.text, {Key? key}) : super(key: key);
  String text;
  @override
  // ignore: library_private_types_in_public_api
  _PageViewTest createState() => _PageViewTest();
}

class _PageViewTest extends State<PageViewTest>
    with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    // ignore: avoid_print
    // print(widget.text);
    return Center(
      child: Text(widget.text),
    );
  }

  @override
  bool get wantKeepAlive => true;
}

class WillPopScopeTestRoute extends StatefulWidget {
  const WillPopScopeTestRoute({super.key});

  @override
  WillPopScopeTestRouteState createState() {
    return WillPopScopeTestRouteState();
  }
}

class WillPopScopeTestRouteState extends State<WillPopScopeTestRoute> {
  DateTime? _lastPressedAt; //上次点击时间

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        if (_lastPressedAt == null ||
            DateTime.now().difference(_lastPressedAt!) > Duration(seconds: 1)) {
          //两次点击间隔超过1秒则重新计时
          _lastPressedAt = DateTime.now();
          return false;
        }
        return true;
      },
      child: Container(
        alignment: Alignment.center,
        child: Text("1秒内连续按两次返回键退出"),
      ),
    );
  }
}
